﻿using System;
using System.Runtime.Caching;

namespace Tyche.Common.Util.Utils
{
    public class CacheUtil
    {
        /// <summary>
        /// 私有构造函数
        /// </summary>
        private CacheUtil()
        {
        }

        /// <summary>
        /// 从缓存获取数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static object Get(string key)
        {
            return MemoryCache.Default.Get(key);
        }

        /// <summary>
        /// 从缓存中获取数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="expire"></param>
        /// <param name="function"></param>
        /// <returns></returns>
        public static T Get<T>(string key, int expire, Func<T> function)
        {
            if (!MemoryCache.Default.Contains(key) && expire > 0)
            {
                var data = function();

                if (data == null)
                {
                    return default(T);
                }

                Set(key, data, expire);
            }

            return (T)MemoryCache.Default.Get(key);
        }

        /// <summary>
        /// 数据写入缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="parameter"></param>
        /// <param name="expire"></param>
        public static void Set(string key, object parameter, int expire)
        {
            MemoryCache.Default.Set(new CacheItem(key, parameter), new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(expire) });
        }

        /// <summary>
        /// 删除缓存
        /// </summary>
        /// <param name="key"></param>
        public static void Remove(string key)
        {
            MemoryCache.Default.Remove(key);
        }
    }
}
